import 'dart:async';
import 'dart:convert';

import 'package:chatbot/wenti.dart';
import 'package:chatbot/yanses.dart';
import 'package:chatbot/shijian.dart';
import 'package:chatbot/shijian_bashi.dart';
import 'package:chatbot/yuyin_tigong.dart';
import 'package:chatbot/juse_yemian.dart';
import 'package:chatbot/liushuju.dart';
import 'package:chatbot/cunchu_guanli.dart';
import 'package:chatbot/three_bounce.dart';
import 'package:chatbot/utils.dart';
import 'package:chatbot/huiyuan_yemian.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

import 'shixian_moxing.dart';
import 'shuju_guanli.dart';

class LiaotianYemian extends StatefulWidget {
  final String tishiCi;
  final String jueseMing;
  final String jueseTishi;
  final int leixing;
  final SpeechToTextProvider kouyuTiGong;
  final SpeechToText shuoHua;
  final String tishiTou;
  final Chuangzuo? chuangZao;

  const LiaotianYemian(
      {super.key,
      required this.tishiCi,
      required this.jueseMing,
      required this.jueseTishi,
      required this.leixing,
      required this.tishiTou,
      required this.shuoHua,
      required this.kouyuTiGong,
      this.chuangZao});

  @override
  State<StatefulWidget> createState() {
    return LiaotianState(
        jueseTishi: tishiCi,
        jueseMing: jueseMing,
        jueseTIshi: jueseTishi,
        tishiTou: tishiTou,
        leixing: leixing,
        chuangzuo: chuangZao);
  }
}

class LiaotianState extends State<LiaotianYemian>
    with AutomaticKeepAliveClientMixin<LiaotianYemian> {
  final String jueseMing;
  final String jueseTIshi;
  final int leixing;
  final String tishiTou;
  bool xianshiYuyin = false;
  List<WenTi> wentiLiebiao = [];
  final TextEditingController shuruKongZhi = TextEditingController();
  var jujiaoJiedian = FocusNode();
  final ScrollController kongzhi = ScrollController();
  late StreamSubscription<bool> jianpanDingYue;
  bool jiazai = false;
  final String jueseTishi;

  FlutterTts yuyinTTS = FlutterTts();
  final Chuangzuo? chuangzuo;

  LiaotianState(
      {required this.jueseTishi,
      required this.jueseMing,
      required this.jueseTIshi,
      required this.leixing,
      required this.tishiTou,
      this.chuangzuo});

  late StreamSubscription eventSubscription;

  String? caidanTou;
  List<String> caidanXiang3 = [];

  String? caidanTou2;
  List<String> caidanXiang2 = [];
  String? morenzhi2;

  String? caidanTou3;
  String? morenzhi3;

  List<String> caidanXiang = [];
  String? morenzhi;

  bool xuyaoSHuruKuang = true;

  @override
  void initState() {
    super.initState();
    // _textEditingController.text = "写一首赞美春天的诗，280字左右。";

    var keyboardVisibilityController = KeyboardVisibilityController();

    // Subscribe
    jianpanDingYue =
        keyboardVisibilityController.onChange.listen((bool visible) {
      debugPrint('Keyboard visibility update. Is visible: $visible');
      if (visible) {
        huaDongDibu();
      }
      CunChuGuanLi.shezhiKeyVisible(visible);
    });
    eventSubscription =
        ShijianGUanli.instance.shijianChe.on<QiehuanJuse>().listen((event) {
      debugPrint("SwitchRoleEvent");
      if (mounted) {
        Future.delayed(const Duration(milliseconds: 500), () {
          setState(() {
            debugPrint("SwitchRoleEvent!!!：${CunChuGuanLi.shouyeJueseTishi()}");
            if (wentiLiebiao.isNotEmpty) {
              wentiLiebiao[0].huida = CunChuGuanLi.shouyeJueseTishi();
            } else {
              wentiLiebiao.add(WenTi(
                  null, CunChuGuanLi.shouyeJueseTishi(), false, false, false));
            }
          });
        });
      }
    });
    shuruKongZhi.addListener(() {
      debugPrint(shuruKongZhi.text);
    });
    wentiLiebiao.add(WenTi(null, jueseTIshi, false, false, false));

    _initSpeech();
    FlutterNativeSplash.remove();
    // _textEditingController.text = "我是一名互联网从业者，男，今年30岁，帮我规划下未来5年的人生规划。";
    if (chuangzuo != null) {
      if (chuangzuo!.candan2 != "") {
        if (chuangzuo!.candan2.contains("-") &&
            chuangzuo!.candan2.contains("|")) {
          List<String> arrays = chuangzuo!.candan2.split("-");
          caidanTou2 = arrays[0];
          List<String> options = arrays[1].split("|");
          morenzhi2 = options[0]; //默认第一个
          // menu2SelectValue = menu2DefaultValue;
          for (String menu in options) {
            caidanXiang2.add(menu);
          }
        }
      }

      if (chuangzuo != null) {
        if (chuangzuo!.caidan != "") {
          if (chuangzuo!.caidan.contains("-") &&
              chuangzuo!.caidan.contains("|")) {
            List<String> arrays = chuangzuo!.caidan.split("-");
            caidanTou = arrays[0];
            List<String> options = arrays[1].split("|");
            morenzhi = options[0]; //默认第一个
            // menuSelectValue = menuDefaultValue;
            for (String menu in options) {
              caidanXiang.add(menu);
            }
          }
        }

        if (chuangzuo!.candan3 != "") {
          if (chuangzuo!.candan3.contains("-") &&
              chuangzuo!.candan3.contains("|")) {
            List<String> arrays = chuangzuo!.candan3.split("-");
            caidanTou3 = arrays[0];
            List<String> options = arrays[1].split("|");
            morenzhi3 = options[0]; //默认第一个
            // menu3SelectValue = menu3DefaultValue;
            for (String menu in options) {
              caidanXiang3.add(menu);
            }
          }
        }
        xuyaoSHuruKuang = chuangzuo!.tishici.contains("{0}");
      }
    }
  }

  void _initSpeech() async {
    await yuyinTTS.setPitch(1.0);
    await yuyinTTS.setSharedInstance(true);
    await yuyinTTS.setVolume(0.5);
    await yuyinTTS.setSpeechRate(0.55);
    await yuyinTTS.awaitSpeakCompletion(true);
    await yuyinTTS.setIosAudioCategory(
        IosTextToSpeechAudioCategory.playback,
        [
          IosTextToSpeechAudioCategoryOptions.allowBluetooth,
          IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
          IosTextToSpeechAudioCategoryOptions.mixWithOthers
        ],
        IosTextToSpeechAudioMode.voicePrompt);
  }

  @override
  void dispose() {
    eventSubscription.cancel();
    jianpanDingYue.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    debugPrint("build");
    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: Yanse.shense,
      appBar: leixing == -1
          ? null
          : AppBar(
              elevation: 0,
              backgroundColor: Yanse.qianse,
              leading: IconButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  icon: const Icon(
                    Icons.arrow_back_ios,
                    color: Colors.black,
                    size: 20,
                  )),
              title: Text(
                jueseMing,
                style: const TextStyle(
                    color: Colors.black,
                    fontSize: 16,
                    fontWeight: FontWeight.w600),
              ),
            ),
      body: GestureDetector(
        onTap: () {
          jujiaoJiedian.unfocus();
        },
        child: Column(
          children: [
            Expanded(
                child: ListView.builder(
                    itemCount: wentiLiebiao.length,
                    controller: kongzhi,
                    itemBuilder: (BuildContext context, int index) {
                      if (index == 0 && chuangzuo != null) {
                        return Container(
                          padding: const EdgeInsets.all(12),
                          color: Yanse.qianse,
                          child: Column(
                            children: [
                              caidanXiang.isNotEmpty
                                  ? xialaCaidan(
                                      caidanTou!, morenzhi!, caidanXiang,
                                      (value) {
                                      setState(() {
                                        morenzhi = value;
                                      });
                                    })
                                  : Container(),
                              caidanXiang2.isNotEmpty
                                  ? xialaCaidan(
                                      caidanTou2!, morenzhi2!, caidanXiang2,
                                      (value) {
                                      setState(() {
                                        morenzhi2 = value;
                                      });
                                    })
                                  : Container(),
                              caidanXiang3.isNotEmpty
                                  ? xialaCaidan(
                                      caidanTou3!, morenzhi3!, caidanXiang3,
                                      (value) {
                                      setState(() {
                                        morenzhi3 = value;
                                      });
                                    })
                                  : Container(),
                            ],
                          ),
                        );
                      } else {
                        return WentiView(
                            question: wentiLiebiao[index],
                            jueseTishi: jueseTishi,
                            huadongKongzhi: kongzhi,
                            wentiStateHuiDiao: (isLoading) {
                              if (!isLoading) {
                                Future.delayed(
                                    const Duration(milliseconds: 500), () {
                                  this.jiazai = isLoading;
                                  if (mounted) {
                                    setState(() {});
                                  }
                                });
                              }
                              debugPrint("isLoading=$isLoading");
                            },
                            jujiaoJiedian: jujiaoJiedian,
                            tts: yuyinTTS,
                            isChuangzuo: chuangzuo != null);
                      }
                    })),
            xuyaoSHuruKuang
                ? Container(
                    height: (chuangzuo == null ? 46 : 96) +
                        MediaQuery.of(context).padding.bottom,
                    width: width,
                    color: Yanse.qianse,
                    padding: EdgeInsets.only(
                      top: 6,
                      bottom: MediaQuery.of(context).padding.bottom,
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 6,
                        ),
                        IconButton(
                            onPressed: () {
                              showModalBottomSheet(
                                context: context,
                                isDismissible: false,
                                isScrollControlled: true,
                                backgroundColor: Colors.white,
                                // backgroundColor: ChatColors.darkColor,
                                builder: (context) {
                                  return YuYinTiGongApp(
                                    shuohua: widget.shuoHua,
                                    yuyinTiGong: widget.kouyuTiGong,
                                    yuyinDaoWenzi: (String value) {
                                      fasong(value);
                                    },
                                  );
                                },
                              );
                            },
                            icon: Image.asset(
                              'assets/images/mic.png',
                              width: 24,
                              height: 24,
                              // fit: BoxFit.fitWidth,
                            )),
                        Expanded(
                          child: Container(
                            alignment: Alignment.center,
                            height: (chuangzuo == null ? 46 : 96),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(
                                Radius.circular((chuangzuo == null ? 23 : 12)),
                              ),
                              color: Yanse.shense,
                            ),
                            child: TextField(
                              controller: shuruKongZhi,
                              style: const TextStyle(color: Colors.black),
                              keyboardType: TextInputType.text,
                              focusNode: jujiaoJiedian,
                              cursorColor: Yanse.jibenYanse,
                              maxLines: chuangzuo == null ? 2 : 18,
                              onChanged: (result) {
                                setState(() {
                                  //更新发送按钮颜色
                                });
                              },
                              onSubmitted: (text) {
                                fasong(shuruKongZhi.text.trim());
                              },
                              textInputAction: jiazai
                                  ? TextInputAction.done
                                  : TextInputAction.send,
                              // textAlignVertical: TextAlignVertical.center,
                              decoration: InputDecoration(
                                  contentPadding:
                                      EdgeInsets.fromLTRB(10, 5, 10, 0),
                                  border: InputBorder.none,
                                  hintText: tishiTou,
                                  hintStyle: TextStyle(
                                      color: Colors.grey, fontSize: 15)),
                            ),
                          ),
                        ),
                        Container(
                          width: 6,
                        ),
                        jiazai
                            ? InkWell(
                                onTap: () {
                                  ShijianGUanli.instance.shijianChe
                                      .fire(TingzhiHUida());
                                },
                                child: SizedBox(
                                  width: 33,
                                  height: 33,
                                  child: Icon(Icons.stop_circle_outlined,
                                      size: 33, color: Yanse.jibenYanse),
                                ),
                              )
                            : InkWell(
                                //单击事件响应
                                onTap: () {
                                  // setState

                                  if (shuruKongZhi.text.isEmpty) {
                                    if (wentiLiebiao.length > 1) {
                                      setState(() {
                                        wentiLiebiao.clear();
                                        wentiLiebiao.add(WenTi(null, jueseTIshi,
                                            false, false, false));
                                      });
                                      Utils.xianshiTishi("已开启新对话");
                                    } else {
                                      Utils.xianshiTishi("已经是新对话啦，继续聊吧");
                                    }
                                  } else {
                                    fasong(shuruKongZhi.text.trim());
                                  }
                                },
                                child: shuruKongZhi.text.isEmpty
                                    ? Image.asset(
                                        'assets/images/refresh.png',
                                        width: 24,
                                        height: 24,
                                        color: Colors.black,
                                        // fit: BoxFit.fitWidth,
                                      )
                                    : Container(
                                        width: 32,
                                        height: 32,
                                        decoration: BoxDecoration(
                                          color: Yanse.jibenYanse,
                                          borderRadius: const BorderRadius.all(
                                              Radius.circular(18.0)),
                                        ),
                                        child: Image.asset(
                                          'assets/images/send.png',
                                          width: 26,
                                          height: 26,
                                          color: Colors.white,
                                          // fit: BoxFit.fitWidth,
                                        ))),
                        Container(
                          width: 12,
                        )
                      ],
                    ),
                  )
                : InkWell(
                    highlightColor: Colors.transparent, // 透明色
                    splashColor: Colors.transparent, //
                    onTap: () {
                      fasong(shuruKongZhi.text.trim());
                    },
                    child: Container(
                        alignment: Alignment.center,
                        width: MediaQuery.of(context).size.width - 72,
                        height: 42,
                        margin: EdgeInsets.only(
                            bottom: 24 + MediaQuery.of(context).padding.bottom),
                        decoration: BoxDecoration(
                          color: jiazai ? Yanse.shense : Yanse.jibenYanse,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(8.0)),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            jiazai
                                ? const Padding(
                                    padding: EdgeInsets.only(right: 8.0),
                                    child: CupertinoActivityIndicator(
                                        radius: 10.0, color: Colors.black),
                                  )
                                : Container(),
                            Text(
                              jiazai ? "停止创作" : "开始创作",
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w600),
                            ),
                          ],
                        )),
                  ),
          ],
        ),
      ),
    );
  }

  void huaDongDibu() {
    Future.delayed(const Duration(milliseconds: 500), () {
      kongzhi.animateTo(
        kongzhi.position.maxScrollExtent,
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeIn,
      );
    });
  }

  void fasong(String wenzi) {
    if (chuangzuo != null) {
      if (shuruKongZhi.text != "" || !xuyaoSHuruKuang) {
        String prompt = chuangzuo!.tishici;
        if (morenzhi != null) {
          prompt = prompt.replaceAll("{1}", morenzhi!);
        }

        if (morenzhi2 != null) {
          prompt = prompt.replaceAll("{2}", morenzhi2!);
        }

        if (morenzhi3 != null) {
          prompt = prompt.replaceAll("{3}", morenzhi3!);
        }

        if (prompt.contains("{0}")) {
          prompt = prompt.replaceAll("{0}", shuruKongZhi.text.trim());
        }
        wenzi = prompt;
      }
    }
    if (wenzi.isNotEmpty) {
      for (WenTi question in wentiLiebiao) {
        question.zuihou = false;
      }
      bool needContext = wentiLiebiao.length > 1;
      wentiLiebiao.add(WenTi(wenzi, null, false, true, needContext));
      jiazai = true;
      shuruKongZhi.text = "";
      FocusScope.of(context).unfocus(); //隐藏软键盘
      huaDongDibu();
    }
  }

  xialaCaidan(String tiaoti, String xialazhi, List<String> liebiaos,
      xialaHuidiao callBack) {
    debugPrint("title=$tiaoti,dropdownValue=$xialazhi,size=${liebiaos.length}");
    return Container(
      width: MediaQuery.of(context).size.width - 32,
      height: 42,
      padding: const EdgeInsets.only(left: 12, right: 12),
      margin: const EdgeInsets.only(top: 12),
      // decoration: BoxDecoration(
      //   border: Border.all(
      //       color: ChatColors.darkColor.withOpacity(0.9), width: 1),
      //   borderRadius: const BorderRadius.all(Radius.circular(4.0)),
      // ),
      child: Row(
        children: [
          Text(
            tiaoti,
            style: const TextStyle(
                color: Colors.black, fontSize: 15, fontWeight: FontWeight.w500),
          ),
          Expanded(child: Container()),
          DropdownButton<String>(
            underline: Container(),
            dropdownColor: Yanse.qianseCeshi,
            style: const TextStyle(
                color: Colors.black, fontSize: 15, fontWeight: FontWeight.w500),
            value: xialazhi,
            onChanged: (String? newValue) {
              if (newValue != null) {
                callBack(newValue);
              }
            },
            items: liebiaos.map<DropdownMenuItem<String>>((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class WentiView extends StatefulWidget {
  final WenTi question;
  final ScrollController huadongKongzhi;
  final WentiStateHuiDiao wentiStateHuiDiao;
  final String jueseTishi;
  final FocusNode jujiaoJiedian;
  final FlutterTts tts;
  final bool isChuangzuo;

  const WentiView(
      {super.key,
      required this.question,
      required this.jueseTishi,
      required this.huadongKongzhi,
      required this.wentiStateHuiDiao,
      required this.jujiaoJiedian,
      required this.tts,
      required this.isChuangzuo});

  @override
  State<StatefulWidget> createState() {
    return WentizhuangTai(
        wenti: question,
        jueseTishi: jueseTishi,
        gundongKongzhi: huadongKongzhi,
        wentiStateHuidiao: wentiStateHuiDiao);
  }
}

class WentizhuangTai extends State<WentiView> {
  StreamController<LiuShuju>? liuKongzhi;
  StreamTransformer<Uint8List, List<int>> unit8Transformer =
      StreamTransformer.fromHandlers(
    handleData: (data, sink) {
      sink.add(List<int>.from(data));
    },
  );
  final WenTi wenti;
  final ScrollController gundongKongzhi;
  final WentiStateHuiDiao wentiStateHuidiao;
  final String jixuTishi = "继续";
  final String jueseTishi;
  bool bofang = false;
  late StreamSubscription shijianDingyue;

  WentizhuangTai(
      {required this.wenti,
      required this.jueseTishi,
      required this.gundongKongzhi,
      required this.wentiStateHuidiao});

  @override
  void initState() {
    super.initState();

    shijianDingyue =
        ShijianGUanli.instance.shijianChe.on<TingzhiHUida>().listen((event) {
      if (mounted) {
        setState(() {
          wenti.huida ??= "已停止回答。";
          tingzhiHuida();
        });
      }
    });
    if (wenti.huida == null && wenti.tishiCi != null) {
      kaishiHuida(wenti.tishiCi!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        (wenti.tishiCi == null || widget.isChuangzuo)
            ? Container()
            : Container(
                padding: const EdgeInsets.fromLTRB(16, 24, 16, 0),
                width: MediaQuery.of(context).size.width,
                child: Row(
                  children: [
                    Expanded(child: Container()),
                    Container(
                      constraints: BoxConstraints(
                          minWidth: 24,
                          maxWidth: MediaQuery.of(context).size.width * 4 / 5),
                      padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(16),
                            topRight: Radius.circular(16),
                            bottomLeft: Radius.circular(16)),
                        color: Yanse.jibenYanse,
                      ),
                      child: Text(
                        wenti.tishiCi!,
                        style:
                            const TextStyle(color: Colors.white, fontSize: 16),
                        textDirection: TextDirection.ltr,
                        softWrap: true,
                      ),
                    )
                  ],
                ),
              ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              highlightColor: Colors.transparent,
              // 透明色
              splashColor: Colors.transparent,
              // 透明色
              onTap: () {
                if (!CunChuGuanLi.shiFouKeyVisible()) {
                  duihuakUang(context, () {
                    //copy
                    Clipboard.setData(ClipboardData(text: wenti.huida!));
                    Utils.xianshiTishi("复制成功");
                  }, () {
                    //继续
                    if (wenti.tishiCi != null) {
                      kaishiHuida(huoqujixu(wenti.tishiCi!));
                    } else {
                      kaishiHuida(jixuTishi);
                    }
                  }, () {
                    chongxinHuida();
                  }, () {
                    setState(() {});
                  });
                } else {
                  widget.jujiaoJiedian.unfocus();
                }
              },
              onLongPress: () {
                if (!CunChuGuanLi.shiFouKeyVisible()) {
                  duihuakUang(context, () {
                    //copy
                    Clipboard.setData(ClipboardData(text: wenti.huida!));
                    Utils.xianshiTishi("复制成功");
                  }, () {
                    //继续
                    kaishiHuida(jixuTishi);
                  }, () {
                    chongxinHuida();
                  }, () {
                    setState(() {});
                  });
                } else {
                  widget.jujiaoJiedian.unfocus();
                }
              },
              child: Container(
                alignment: Alignment.topLeft,
                padding: const EdgeInsets.fromLTRB(16, 12, 8, 3),
                child: wenti.huida == null
                    ? SizedBox(
                        width: 30,
                        height: 24,
                        child: SpinKitThreeBounce(
                          color: Yanse.jibenYanse,
                          size: 20.0,
                        ),
                      )
                    : Container(
                        constraints: BoxConstraints(
                            minWidth: 24,
                            maxWidth:
                                MediaQuery.of(context).size.width * 4 / 5),
                        padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
                        decoration: BoxDecoration(
                          borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(16),
                              topRight: Radius.circular(16),
                              bottomRight: Radius.circular(16)),
                          color: Yanse.qianse,
                        ),
                        child: Text(
                          wenti.huida!,
                          textAlign: TextAlign.start,
                          style:
                              TextStyle(color: Yanse.shenseZiti, fontSize: 16),
                          textDirection: TextDirection.ltr,
                          softWrap: true,
                        ),
                      ),
              ),
            ),
            (wenti.zuihou && wenti.huida != null)
                ? InkWell(
                    highlightColor: Colors.transparent, // 透明色
                    splashColor: Colors.transparent, // 透明色
                    onTap: () {
                      duihuakUang(context, () {
                        //copy
                        Clipboard.setData(ClipboardData(text: wenti.huida!));
                        Utils.xianshiTishi("复制成功");
                      }, () {
                        //继续
                        kaishiHuida(jixuTishi);
                      }, () {
                        chongxinHuida();
                      }, () {
                        setState(() {});
                      });
                    },
                    child: Container(
                      width: 26,
                      height: 26,
                      decoration: BoxDecoration(
                        borderRadius:
                            const BorderRadius.all(Radius.circular(13)),
                        color: Yanse.qianse,
                      ),
                      child: const Icon(
                        Icons.more_horiz,
                        color: Colors.black,
                        size: 14,
                      ),
                    ),
                  )
                : ((wenti.huida != null && wenti.tishiCi == null)
                    ? InkWell(
                        highlightColor: Colors.transparent, // 透明色
                        splashColor: Colors.transparent, // 透明色
                        onTap: () {
                          Navigator.push(context, CupertinoPageRoute(
                              builder: (BuildContext context) {
                            return const JuseBiaoQianYemian(
                              shifouXuanze: true,
                              shuohua: null,
                              shuohuaTigong: null,
                            );
                          }));
                        },
                        child: Container(
                          width: 26,
                          height: 26,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(13)),
                            color: Yanse.qianse,
                          ),
                          child: const Icon(
                            Icons.swap_vert,
                            color: Colors.black,
                            size: 14,
                          ),
                        ))
                    : Container()),
          ],
        )
      ],
    );
  }

  void kaishiHuida(String prompt) async {
    if (!wenti.jiazai) {
      if (prompt != jixuTishi) {
        if (wenti.huida != null && wenti.huida!.isNotEmpty) {
          wenti.huida = null; //处理重新生成
        }
      }
      String speechText = "";
      debugPrint("startSSE");
      int msgIndex = 0;
      wentiStateHuidiao(true);
      wenti.jiazai = true;
      if (CunChuGuanLi.yunxuyuyin()) {
        bofang = true;
      }
      try {
        Response response = await QingQiuGuanLi.instance.qingqiu.get(
            "chatgpt/chat/sseV2?prompt=$prompt&rolePrompt=$jueseTishi&needContext=${wenti.shagnxiaWen}");
        var lineRegex = RegExp(r'^([^:]*)(?::)?(?: )?(.*)?$');
        var currentSSEModel = LiuShuju(shuju: '', id: '', shijian: '');
        // ignore: close_sinks
        liuKongzhi = StreamController();

        response.data?.stream
            .transform(unit8Transformer)
            .transform(const Utf8Decoder())
            .transform(const LineSplitter())
            .listen(
          (dataLine) {
            if (dataLine.isEmpty) {
              ///This means that the complete event set has been read.
              ///We then add the event to the stream
              liuKongzhi?.add(currentSSEModel);
              currentSSEModel = LiuShuju(shuju: '', id: '', shijian: '');
              return;
            }

            ///Get the match of each line through the regex
            Match match = lineRegex.firstMatch(dataLine)!;
            var field = match.group(1);
            if (field!.isEmpty) {
              debugPrint("换行？");
              return;
            }
            var value = '';
            if (field == 'data') {
              //If the field is data, we get the data through the substring
              value = dataLine.substring(
                5,
              );
            } else {
              value = match.group(2) ?? '';
            }
            switch (field) {
              case 'event':
                currentSSEModel.shijian = value;
                break;
              case 'data':
                currentSSEModel.shuju = (currentSSEModel.shuju ?? '') + value;

                break;
              case 'id':
                currentSSEModel.id = value;
                break;
              case 'retry':
                break;
            }
          },
          onError: (e, s) {
            debugPrint('---ERROR---');
            debugPrint(e);
            wenti.jiazai = false;
            wentiStateHuidiao(false);
            liuKongzhi?.addError(e, s);
          },
          onDone: () {
            wenti.jiazai = false;
            wentiStateHuidiao(false);
            debugPrint('Done!');
            gundongDibu();
            if (wenti.huida != null &&
                wenti.huida!.contains(Utils.meiyoushiyong)) {
              Future.delayed(const Duration(milliseconds: 1500), () {
                Navigator.push(context,
                    CupertinoPageRoute(builder: (BuildContext context) {
                  return HuiYuanYeMian(
                      "聊天-${CunChuGuanLi.shouyeJueseMing()}-${wenti.tishiCi}");
                }));
              });
            }
          },
        );

        liuKongzhi?.stream.listen((event) {
          setState(() {
            String? msg = event.shuju;
            if (msg != null) {
              if (msg.isEmpty) {
                if (wenti.huida != null && !(wenti.huida!.endsWith("\n"))) {
                  msg = "\n";
                }
              }
              if (wenti.huida == null) {
                wenti.huida = msg;
                speechText = msg;
              } else {
                if (wenti.huida == "已停止回答。") {
                  wenti.huida = "";
                }
                wenti.huida = "${wenti.huida}$msg";
                speechText = "$speechText$msg";
                msgIndex += 1;
              }
              if (CunChuGuanLi.yunxuyuyin()) {
                if (msgIndex <= 1) {
                  Future.delayed(const Duration(milliseconds: 500), () {
                    widget.tts.setLanguage(getLan(speechText));
                    widget.tts.speak(speechText);
                    speechText = "";
                    widget.tts.setCompletionHandler(() {
                      if (speechText.isNotEmpty) {
                        widget.tts.setLanguage(getLan(speechText));
                        widget.tts.speak(speechText);
                        speechText = "";
                      } else {
                        if (mounted) {
                          setState(() {
                            bofang = false;
                          });
                        }
                      }
                    });
                  });
                }
              }

              if (msgIndex % 20 == 0) {
                gundongDibu();
              }
            }
          });
        });
      } catch (e) {
        debugPrint('Error making request: $e');
      }
    }
  }

  void chongxinHuida() {
    if (wenti.jiazai) {
      setState(() {
        wenti.jiazai = false;
        wenti.huida ??= "已停止回答。";
        tingzhiHuida();
      });
    } else {
      kaishiHuida(wenti.tishiCi!);
    }
  }

  void bofangHuida() {
    if (wenti.huida != null && wenti.huida!.isNotEmpty) {
      if (bofang) {
        widget.tts.stop();
        if (mounted) {
          setState(() {
            bofang = false;
          });
        }
      } else {
        if (mounted) {
          setState(() {
            bofang = true;
          });
        }

        widget.tts.setLanguage(getLan(wenti.huida!));
        widget.tts.speak(wenti.huida!);
        widget.tts.setCompletionHandler(() {
          if (mounted) {
            setState(() {
              bofang = false;
            });
          }
        });
      }
    }
  }

  void tingzhiHuida() {
    liuKongzhi?.close();
    wenti.jiazai = false;
  }

  void duihuakUang(context, VoidCallback fuzhi, VoidCallback jixu,
      VoidCallback shuaxin, VoidCallback qiehuan) {
    showDialog(
      context: context,
      barrierDismissible: true,
      // barrierColor: Color(0x01000000),
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          content: SizedBox(
            height: 172.0,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                InkWell(
                  highlightColor: Colors.transparent, // 透明色
                  splashColor: Colors.transparent, // 透明色
                  onTap: () {
                    fuzhi();
                    Navigator.pop(context);
                  },
                  child: const Row(
                    children: <Widget>[
                      Icon(
                        Icons.copy,
                        size: 24,
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 12.0),
                        child: Text(
                          '复制',
                          style: TextStyle(color: Colors.black, fontSize: 15),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(
                  height: 20.0,
                ),
                InkWell(
                    highlightColor: Colors.transparent, // 透明色
                    splashColor: Colors.transparent, // 透明色
                    onTap: () {
                      if (wenti.tishiCi != null) {
                        jixu();
                      }
                      Navigator.pop(context);
                    },
                    child: const Row(
                      children: <Widget>[
                        Icon(
                          Icons.play_circle_outline,
                          size: 24,
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 12.0),
                          child: Text('继续',
                              style:
                                  TextStyle(color: Colors.black, fontSize: 15)),
                        ),
                      ],
                    )),
                const SizedBox(
                  height: 20.0,
                ),
                InkWell(
                    highlightColor: Colors.transparent, // 透明色
                    splashColor: Colors.transparent, // 透明色
                    onTap: () {
                      if (wenti.tishiCi != null) {
                        shuaxin();
                      }
                      Navigator.pop(context);
                    },
                    child: const Row(
                      children: <Widget>[
                        Icon(
                          Icons.sync,
                          size: 26,
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 12.0),
                          child: Text('重新生成',
                              style:
                                  TextStyle(color: Colors.black, fontSize: 15)),
                        ),
                      ],
                    )),
                const SizedBox(
                  height: 20.0,
                ),
                InkWell(
                    highlightColor: Colors.transparent, // 透明色
                    splashColor: Colors.transparent, // 透明色
                    onTap: () {
                      CunChuGuanLi.shezhiYuyinYunsu(
                          !CunChuGuanLi.yunxuyuyin());
                      qiehuan();
                      Navigator.pop(context);
                    },
                    child: Row(
                      children: <Widget>[
                        const Icon(
                          Icons.mic_off,
                          size: 26,
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 12.0),
                          child: Text(
                              CunChuGuanLi.yunxuyuyin()
                                  ? '关闭语音跟读'
                                  : "开启语音跟读",
                              style: const TextStyle(
                                  color: Colors.black, fontSize: 15)),
                        ),
                      ],
                    )),
              ],
            ),
          ),
        );
      },
    );
  }

  String huoqujixu(String string) {
    String lanc = '继续';

    final RegExp persian = RegExp('[\u0600-\u06FF]+');
    final RegExp english = RegExp('[a-zA-Z]+');
    final RegExp arabic = RegExp('[\u0621-\u064A]+');
    final RegExp chinese = RegExp('[\u4E00-\u9FFF]+');
    final RegExp japanese = RegExp('[\u3040-\u30FF]+');
    final RegExp korean = RegExp('[\uAC00-\uD7AF]+');
    final RegExp ukrainian = RegExp('[\u0400-\u04FF\u0500-\u052F]+');
    final RegExp russian = RegExp('[\u0400-\u04FF]+');
    final RegExp italian = RegExp('[\u00C0-\u017F]+');
    final RegExp french = RegExp('[\u00C0-\u017F]+');
    final RegExp spanish = RegExp(
        '[\u00C0-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF\u1D00-\u1D7F]+');

    if (persian.hasMatch(string)) lanc = "ادامه هید";
    if (english.hasMatch(string)) lanc = 'continue';
    if (arabic.hasMatch(string)) lanc = "يكمل";
    if (chinese.hasMatch(string)) lanc = '继续';
    if (japanese.hasMatch(string)) lanc = '続く';
    if (korean.hasMatch(string)) lanc = '계속하다';
    if (russian.hasMatch(string)) lanc = 'продолжать';
    if (ukrainian.hasMatch(string)) lanc = 'продовжувати';
    if (italian.hasMatch(string)) lanc = 'Continua';
    if (french.hasMatch(string)) lanc = 'continuer';
    if (spanish.hasMatch(string)) lanc = 'continuar';

    return lanc;
  }

  String getLan(String string) {
    String lanc = 'zh-CN';

    final RegExp persian = RegExp('[\u0600-\u06FF]+');
    final RegExp english = RegExp('[a-zA-Z]+');
    final RegExp arabic = RegExp('[\u0621-\u064A]+');
    final RegExp chinese = RegExp('[\u4E00-\u9FFF]+');
    final RegExp japanese = RegExp('[\u3040-\u30FF]+');
    final RegExp korean = RegExp('[\uAC00-\uD7AF]+');
    final RegExp ukrainian = RegExp('[\u0400-\u04FF\u0500-\u052F]+');
    final RegExp russian = RegExp('[\u0400-\u04FF]+');
    final RegExp italian = RegExp('[\u00C0-\u017F]+');
    final RegExp french = RegExp('[\u00C0-\u017F]+');
    final RegExp spanish = RegExp(
        '[\u00C0-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF\u1D00-\u1D7F]+');

    if (persian.hasMatch(string)) lanc = 'fa-IR';
    if (english.hasMatch(string)) lanc = 'en-US';
    if (arabic.hasMatch(string)) lanc = 'ar-SA';
    if (chinese.hasMatch(string)) lanc = 'zh-CN';
    if (japanese.hasMatch(string)) lanc = 'ja-JP';
    if (korean.hasMatch(string)) lanc = 'ko-KR';
    if (russian.hasMatch(string)) lanc = 'ru-RU';
    if (ukrainian.hasMatch(string)) lanc = 'uk-UA';
    if (italian.hasMatch(string)) lanc = 'it-IT';
    if (french.hasMatch(string)) lanc = 'fr-FR';
    if (spanish.hasMatch(string)) lanc = 'es-ES';

    return lanc;
  }

  Map<String, String> voiceJixu = {
    "普通话": "继续",
    "英语": "continue",
    "法语": "continuer",
    "韩语": "계속하다",
    "日语": "続く",
    "意大利语": "Continua",
    "西班牙语": "continuar",
    "俄语": "продолжать",
    "乌克兰语": "продовжувати",
    "阿拉伯语": "يكمل",
    "波斯语": "ادامه هید"
  };

  void gundongDibu() {
    gundongKongzhi.animateTo(
      gundongKongzhi.position.maxScrollExtent,
      duration: const Duration(milliseconds: 500),
      curve: Curves.linear,
    );
  }

  @override
  void dispose() {
    super.dispose();
    shijianDingyue.cancel();
    tingzhiHuida();
  }
}

typedef WentiStateHuiDiao = void Function(bool isLoading);

typedef shuoDaoXieHuiDiao = void Function(String value);
typedef xialaHuidiao = void Function(String? value);
